import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:get/get.dart';

import '../../../../../../config/ApiConfig.dart';
import '../../../../../../res/HDColors.dart';
import '../../view/common_widget.dart';
import 'logic.dart';

class WebViewPage extends StatelessWidget {
  final logic = Get.put(WebViewLogic());
  final state = Get.find<WebViewLogic>().state;

  InAppWebViewGroupOptions options = InAppWebViewGroupOptions(
    //夸平台配置
    crossPlatform: InAppWebViewOptions(
      clearCache: true,
      cacheEnabled: false,
      javaScriptCanOpenWindowsAutomatically: true,
      useShouldOverrideUrlLoading: true,
      //加载url拦截功能
      useShouldInterceptAjaxRequest: true,
      //ajax请求拦截
      useOnLoadResource: true,
      //资源加载回调
      allowFileAccessFromFileURLs: true,
      //资源加载
      mediaPlaybackRequiresUserGesture: false, //多媒体控制
    ),
    //Android平台配置
    android: AndroidInAppWebViewOptions(
      cacheMode: AndroidCacheMode.LOAD_NO_CACHE,
      clearSessionCache: true,
      useHybridComposition: true,
      //支持HybridComposition
      useShouldInterceptRequest: true,
      //请求加载链接，可以用于实现Web离线包
      blockNetworkImage: true,
    ),
    //iOS平台配置
    ios: IOSInAppWebViewOptions(
      allowsInlineMediaPlayback: true,
    ),
  );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: HDColors.grayBg,
        appBar: AppBar(centerTitle: true, title: Text(state.title),backgroundColor: HDColors.green,
          leading: CommonWidget.getAppBarLeading(),),
        body: GetBuilder<WebViewLogic>(builder: (logic) {
          // TODO 票样预览中，如果安卓系统过低（如Android7），一般内置的浏览器内核为很低版本，导致前端的新语法不支持，所以会白屏

          return InAppWebView(
            initialUrlRequest: URLRequest(
                url: Uri.parse("${state.url}"),
                method: "GET",
                headers: {"Cookie": "hayden=${ApiConfig.getToken}"}),
            initialOptions: options,
            onReceivedServerTrustAuthRequest: (controller, challenge) async {
              //解决 handshake failed问题
              return ServerTrustAuthResponse(
                  action: ServerTrustAuthResponseAction.PROCEED);
            },
            onWebViewCreated: (InAppWebViewController controller) {
              // controller.loadUrl(urlRequest: urlRequest)
            },
            shouldOverrideUrlLoading: (InAppWebViewController controller,
                NavigationAction navigationAction) async {
              print("shouldOverrideUrlLoading------------${navigationAction.request.headers}");

              return NavigationActionPolicy.ALLOW;
            },
            onLoadStart: (InAppWebViewController controller, Uri? url) {
              print("onLoadStart------path-------${url?.path}");
              print("onLoadStart------queryParameters-------${url?.queryParameters}");
            },
            onLoadStop: (InAppWebViewController controller, Uri? url) {
              // controller.evaluateJavascript(source: '');
              // controller.evaluateJavascript(source: 'document.cookie="hayden=${ApiConfig.getToken};"');

              print("onLoadStop-------------${url?.path}");
            },
            onProgressChanged:
                (InAppWebViewController controller, int progress) {
              print("onProgressChanged-----------------$progress");
            },
            onLoadError: (InAppWebViewController controller, Uri? url, int code,
                String message) {
              print(
                  "onLoadError-------------${url?.path}----$code----$message");
            },
            onLoadHttpError: (InAppWebViewController controller, Uri? url,
                int statusCode, String description) {
              print(
                  "onLoadHttpError-------------${url?.path}----$statusCode----$description");
            },
            onConsoleMessage: (InAppWebViewController controller,
                ConsoleMessage consoleMessage) {
              print(
                  "onConsoleMessage-------------${consoleMessage.message}----${consoleMessage.messageLevel}");
            },
            onLoadResource:
                (InAppWebViewController controller, LoadedResource resource) {
              print("onLoadResource-------------");
            },
            onPrint: (InAppWebViewController controller, Uri? url) {
              print("onPrint-------------${url?.path}");
            },
          );
        }));
  }
}
